﻿using DotPowerJob.Requests;
using Flurl;
using Flurl.Http;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DotPowerJob.Responses;
using System.Linq;
using DotPowerJob.Models;
using Microsoft.Extensions.Options;

namespace DotPowerJob.Hosted
{
    /// <summary>
    /// 上报任务状态
    /// </summary>
    public class JobReportInstanceStatus : BackgroundService
    {
        private readonly ILogger _logger;
        private readonly JobDispatcher _dispatcher;
        private readonly PowerJobConfig _jobConfig;
        public JobReportInstanceStatus(ILogger<JobReportInstanceStatus> logger, JobDispatcher dispatcher, IOptions<PowerJobConfig> options)
        {
            this._logger = logger;
            this._dispatcher = dispatcher;

            if (options == null)
                throw new ArgumentNullException(nameof(options));
            this._jobConfig = options.Value;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //while (!stoppingToken.IsCancellationRequested)
            //{
            //    try
            //    {
            //        var runingTasks = this._dispatcher.RUNNING_QUEUE.AsQueryable().ToList();
            //        runingTasks.ForEach(q =>
            //        {
            //            if (this._dispatcher.RUNNING_QUEUE.TryGetValue(q.Key, out var queue))
            //            {
            //                var request = new TaskTrackerReportInstanceStatusRequest()
            //                {
            //                    JobId = 1,
            //                    InstanceId = 100,
            //                    ReportTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
            //                    SourceAddress = this._jobConfig.ClientAddress,
            //                    InstanceStatus = Enum.InstanceStatus.RUNNING
            //                };
            //                var jsonStr = JsonConvert.SerializeObject(request, new JsonSerializerSettings()
            //                {
            //                    ContractResolver = new CamelCasePropertyNamesContractResolver()
            //                });
            //                HttpContent content = new StringContent(jsonStr);

            //                var response = PowerJobCache.ServerAddress.AppendPathSegment("/server/reportInstanceStatus")
            //                    .WithHeader("content-type", "application/json")
            //                    .PostAsync(content)
            //                    .ReceiveJson<PowerJobResponse>()
            //                    .Result;
            //                if (response != null && response.Success)
            //                {
            //                    this._dispatcher.TryRemoveJobTask(q.Key);
            //                }
            //                else if (response == null)
            //                {
            //                    this._logger.LogInformation("Report Instance Status Error,Response Is Null");
            //                }
            //                else
            //                {
            //                    this._logger.LogInformation($"Report Instance Status Faild,Message: {response.Message}");
            //                }
            //            }

            //        });
            //        await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
            //    }
            //    catch (TaskCanceledException)
            //    {
            //        this._logger.LogInformation("--- Application stopping ---");
            //    }
            //    catch (Exception ex)
            //    {
            //        await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
            //        this._logger.LogError(ex, "Report InstanceStatus error:{0}", ex.Message);
            //    }
            //}
        }
    }
}
